import { RunModelPrimitive } from "./example/thing/camera/roleController/RunModelPrimitive.js";

var eventTarget = new mars3d.BaseClass();

      var map;
      var graphicLayer;
      var runModel;

      var mapOptions = {
  scene: {
    center: { lng: 105.9971937909753, lat: 28.27913503096258, alt: 1000, heading: 0, pitch: -30 },
    showSun: true,
    showMoon: true,
    showSkyBox: true,
    showSkyAtmosphere: true,
    fog: true,
    fxaa: true,
    globe: {
      showGroundAtmosphere: false, // 关闭大气（球表面白蒙蒙的效果）
      depthTestAgainstTerrain: true,
      baseColor: "#546a53"
    },
    cameraController: {
      zoomFactor: 20.0,
      minimumZoomDistance: 1,
      maximumZoomDistance: 50000000,
      enableRotate: true,
      enableZoom: true
    },
    mapProjection: mars3d.CRS.EPSG3857, // 2D下展示墨卡托投影
    mapMode2D: Cesium.MapMode2D.INFINITE_SCROLL // 2D下左右一直可以滚动重复世界地图
  },
  terrain:{
    url: "http://data.mars3d.cn/terrain",
    show: true
  },
  basemaps: [
    {
      name: "天地图影像",
      icon: "https://data.mars3d.cn/img/thumbnail/basemap/tdt_img.png",
      type: "tdt",
      layer: "img_d",
      show: true
    }
  ],
  control: {
    compass: { style: { top: "10px", left: "5px" } }
  }
}

function initMap() {
  try {
    console.log("正在初始化地图...");
    // 检查dom元素是否存在
    var mapContainer = document.getElementById("mars3dContainer");
    if (!mapContainer) {
      console.error("地图容器元素不存在!");
      return null;
    }
    // 确认必要的库已加载
    if (typeof mars3d === 'undefined') {
      console.error("mars3d库未加载!");
      return null;
    }
    if (typeof Cesium === 'undefined') {
      console.error("Cesium库未加载!");
      return null;
    }
    // 创建三维地球场景
    map = new mars3d.Map("mars3dContainer", mapOptions);
    
    // 监听地形加载事件
    map.on(mars3d.EventType.terrainLoadSuccess, function(event) {
      console.log("地形服务加载成功", event);
    });
    map.on(mars3d.EventType.terrainLoadError, function(event) {
      console.log("地形服务加载失败", event);
    });
    
    return map;
  } catch (error) {
    console.error("地图初始化失败:", error);
    // 显示错误信息到页面上
    var mapContainer = document.getElementById("mars3dContainer");
    if (mapContainer) {
      mapContainer.innerHTML = '<div style="color:red;padding:20px;">地图加载失败: ' + error.message + '</div>';
    }
    return null;
  }
}
var wolfModel;
var mushroomModel
//添加静止模型
function addStaticModel() {
  const lon = 121.998; // 自定义经度
  const lat = 48.2795; // 自定义纬度

  wolfModel = new mars3d.graphic.ModelEntity({
    name: "静止模型",
    position: Cesium.Cartesian3.fromDegrees(lon, lat),
    style: {
      url: "Wolf.gltf", // 确保模型路径正确（或使用完整URL）
      scale: 1.0,
      minimumPixelSize: 100,
      heading: 0,     // 朝向角度
      pitch: 0,
      roll: 0,
      heightReference:Cesium.HeightReference.CLAMP_TO_GROUND, // 不贴地，使用固定高度
    }
  });

  const lon2 = 121.993; // 自定义经度
  const lat2 = 48.2795; // 自定义纬度
  mushroomModel = new mars3d.graphic.ModelEntity({
    name: "静止模型",
    position: Cesium.Cartesian3.fromDegrees(lon2, lat2),
    style: {
      url: "./mushroom_gltf/scene.gltf", // 确保模型路径正确（或使用完整URL）
      scale: 1.0,
      minimumPixelSize: 100,
      heading: 0,     // 朝向角度
      pitch: 0,
      roll: 0,
      heightReference:Cesium.HeightReference.CLAMP_TO_GROUND, // 不贴地，使用固定高度
    }
  });

  // 添加模型到图层
  graphicLayer.addGraphic(wolfModel);
  graphicLayer.addGraphic(mushroomModel);
}

// 距离计算函数
function getFlatDistance(lon1, lat1, lon2, lat2) {
  const R = 6371000; // 地球半径，单位米
  const toRad = Math.PI / 180;
  const dLat = (lat2 - lat1) * toRad;
  const dLon = (lon2 - lon1) * toRad;
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * toRad) * Math.cos(lat2 * toRad) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

//碰撞检测函数
function startCollisionCheck() {
  let hasCollidedWolf = false;
  let hasCollidedMushroom = false;

  setInterval(() => {
    if (!runModel || !wolfModel) {
      console.log("模型未就绪", runModel, wolfModel);
      return;
    }

    // 获取模型的经纬度
    let stagPos = runModel.position;
    if (!Array.isArray(stagPos)) {
      const carto = Cesium.Cartographic.fromCartesian(stagPos);
      stagPos = [
        Cesium.Math.toDegrees(carto.longitude),
        Cesium.Math.toDegrees(carto.latitude)
      ];
    }
    let wolfPos = wolfModel.position;
    if (!Array.isArray(wolfPos)) {
      const carto = Cesium.Cartographic.fromCartesian(wolfPos);
      wolfPos = [
        Cesium.Math.toDegrees(carto.longitude),
        Cesium.Math.toDegrees(carto.latitude)
      ];
    }
    let mushroomPos = mushroomModel.position;
    if (!Array.isArray(mushroomPos)) {
      const carto = Cesium.Cartographic.fromCartesian(mushroomPos);
      mushroomPos = [
        Cesium.Math.toDegrees(carto.longitude),
        Cesium.Math.toDegrees(carto.latitude)
      ];
    }

  

    // 只用经纬度算距离
    const dist = getFlatDistance(stagPos[0], stagPos[1], wolfPos[0], wolfPos[1]);
    const dist2 = getFlatDistance(stagPos[0], stagPos[1], mushroomPos[0], mushroomPos[1]);
    console.log("当前平面距离：", dist2);

    //计算狼距离
   if (dist < 30 && !hasCollidedWolf) {
     hasCollidedWolf = true;
     // 显示自定义弹窗
     const popup = document.getElementById('collision-popup');
     if (popup) popup.style.display = 'flex';
   }
   // 关闭按钮事件（只需绑定一次即可）
   document.getElementById('popup-close-btn').onclick = function() {
      document.getElementById('collision-popup').style.display = 'none';
   };
    if (dist >= 30) {
      hasCollidedWolf = false;
    }

    //计算蘑菇距离
    if (dist2 < 30 && !hasCollidedMushroom) {
      hasCollidedMushroom = true;
      // 显示自定义弹窗
      const popup2 = document.getElementById('collision-popup1');
      if (popup2) popup2.style.display = 'flex';
     }
     document.getElementById('popup-close-btn1').onclick = function() {
      document.getElementById('collision-popup1').style.display = 'none';
   };
    if (dist2 >= 30) {
      hasCollidedMushroom = false;
    }
  }, 300);
}

function onMounted(mapInstance) {
  map = mapInstance;

  graphicLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayer);

  graphicLayer.on(mars3d.EventType.click, function (event) {
    console.log("监听layer，单击了矢量对象", event);
  });

  // 采样和添加模型的函数
  function addModelAfterTerrain() {
    const lon = 121.9941937909753;
    const lat = 48.278;
    const offset = 0;
    const carto = Cesium.Cartographic.fromDegrees(lon, lat);

    Cesium.sampleTerrainMostDetailed(map.scene.terrainProvider, [carto]).then(function(results) {
      const height = (results[0].height || 0) + offset;
      runModel = new RunModelPrimitive({
        position: [lon, lat, height],
        style: {
          url: "Stag.gltf",
          heading: -90,
          minimumPixelSize: 100,
          animation: "run"
        },
        speed: 2,
        clampToGround: true,
        groundOffset: offset
      });

      graphicLayer.addGraphic(runModel);
      // 启动碰撞检测
    startCollisionCheck();
    });
  }
  // 监听地形加载成功后再添加模型
  map.on(mars3d.EventType.terrainLoadSuccess, function() {
    addModelAfterTerrain();
    addStaticModel();
  });

  // 如果地形已经加载好，也直接添加
  if (map.scene.terrainProvider.ready) {
    addModelAfterTerrain();
    addStaticModel();
  }
}

      function onUnmounted() {
        map = null;
      }

      function setEnabled(val) {
        runModel.show = val;
      }

      // 控制器启动函数
      var canClick = true;
      function clickStartController() {
        setTimeout(() => {
          canClick = true;
        }, 500);
        if (canClick) {
          canClick = false;
        }
      }

      // 页面加载时自动启动角色控制
      window.addEventListener("load", function () {
         const mapInstance = initMap();
  if (mapInstance) {
    onMounted(mapInstance);
  } else {
    console.warn("mapInstance未创建，onMounted未执行");
  }
  clickStartController();
      });